package com.leyou.auth.web;

import com.leyou.auth.service.IAuthService;
import com.leyou.common.auth.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理请求和响应的方法
 *
 * @version V1.0
 * @package com.leyou.auth.web
 * @description:
 * @author: pc
 * @date: 2019/7/10 22:24
 */
@RestController
public class AuthController {
    @Autowired
    private IAuthService authService;

    /**
     * 用户登入操作
     * 生成token，并保存到cookie中
     * */
    @PostMapping("login")
    public ResponseEntity<Void> userLogin(@RequestParam("username")String username,
                                          @RequestParam("password")String password,
                                          HttpServletResponse response) {
        authService.userLogin(username,password,response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户登录后的校验操作
     * 从cookie中读取token
     * */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> userVerify(HttpServletRequest request,HttpServletResponse response) {
        UserInfo userInfo = authService.userVerify(request,response);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 用户的登出
     * */
    @PostMapping("logout")
    public ResponseEntity<Void> userLogout(HttpServletRequest request, HttpServletResponse response) {
        authService.userLogout(request,response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("authorization")
    public ResponseEntity<String> authorize(@RequestParam("id") Long id, @RequestParam("secret") String secret) {
        String result = authService.authenticate(id, secret);
        return ResponseEntity.ok(result);
    }

}
